package com.module.login.model

import cn.leancloud.LCInstallation
import cn.leancloud.LCObject
import cn.leancloud.LCQuery
import com.module.app.base.BaseViewModel
import com.module.app.ext.loginFlow
import com.module.base.ext.request
import com.module.base.utils.AppUtils
import com.module.base.utils.CommonUtils
import com.module.base.utils.ToastUtils
import com.module.frame.ext.postEvent
import com.module.login.R
import com.module.login.utils.loginPush
import com.module.third.learcloud.*
import kotlinx.coroutines.flow.MutableSharedFlow

class LoginCodeViewModel : BaseViewModel() {

    /**
     * 发送验证码
     */
    var sendCodeFlow: MutableSharedFlow<Boolean> = MutableSharedFlow()

    /**
     * 验证验证码
     */
    var verifyCodeFlow: MutableSharedFlow<Boolean> = MutableSharedFlow()


    fun sendCode(phone: String) {
        request({
            lcSendCode(phone, 10, CommonUtils.getString(R.string.app_name), "登录")
        }, {
            ToastUtils.showShort("短信发送成功,请注意查收")
            postEvent(sendCodeFlow,true)
        }, {
            it.msg?.let { msg ->
                ToastUtils.showShort(msg)
            }
        }, true)
    }

    fun verifyCode(phone: String, code: String) {
        request({
            lcVerifyCode(phone, code)
        }, {
            postEvent(verifyCodeFlow,true)
        }, {
            postEvent(verifyCodeFlow,false)
            it.msg?.let { msg ->
                ToastUtils.showShort(msg)
            }
        }, true)
    }

    fun login(phone: String) {
        request({
            //查询账号
            var response: LCResponse<com.module.app.bean.UserBean> = queryPhone(phone)
            //判断是否是新号还是已登录过了
            saveUserBean(phone, response.getData())
        }, {
            check(it != null) {
                CommonUtils.getString(R.string.error_unknow)
            }
            com.module.app.utils.UserUtils.setUserBean(it)
            postEvent(loginFlow, true)
        }, {
            it.msg?.let { msg ->
                ToastUtils.showShort(msg)
            }
        }, true)
    }

    /**
     * 查询用户信息
     */
    private suspend fun queryPhone(phone: String): LCResponse<com.module.app.bean.UserBean> {
        val tClass = com.module.app.bean.UserBean::class.java
        val query = LCQuery<LCObject>(tClass.simpleName)
        query.whereEqualTo("phone", phone)
        return lcQuerySingle(query, tClass)
    }

    /**
     * 更新或者上传用户信息
     */
    private suspend fun saveUserBean(
        phone: String,
        resultUserBean: com.module.app.bean.UserBean?
    ): LCResponse<com.module.app.bean.UserBean> {
        val userBean: com.module.app.bean.UserBean
        var objectId: String? = null
        if (resultUserBean == null) {
            //数据为空创建账号
            userBean = com.module.app.bean.UserBean()
            userBean.loginType = com.module.app.bean.IType.ILogin.PHONE
            userBean.phone = phone
        } else {
            //数据不为空，更新账号  ,更新设备id
            userBean = resultUserBean
            objectId = userBean.objectId
            //如果设备id不是当前设备，则发送推送
            if (userBean.deviceId != null && userBean.deviceId != AppUtils.getAndroidId()) {
                loginPush(userBean.pushId)
            }
        }
        userBean.deviceId = AppUtils.getAndroidId()
        userBean.pushId = LCInstallation.getCurrentInstallation().installationId
        return lcSave(userBean, objectId, com.module.app.bean.UserBean::class.java)
    }
}